<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import {
  GetPlanExamsApi,
  DeletePlanExamsApi,
  AddCourseExamApi,
  UpdatePlanExamApi
} from '@/api/course'

import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/examinationlogWrite.vue'
import Detail from './components/examinationlogDetail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

import { useButtonPermiss } from '@/utils/buttonpermiss'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()

import { useUserStoreWithOut } from '@/store/modules/user'
import { ElTag } from 'element-plus'
const userStore = useUserStoreWithOut()

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await GetPlanExamsApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })

    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount || 0
    }
  },
  fetchDelApi: async () => {
    const res = await DeletePlanExamsApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const getCurrentMonthDates = () => {
  const currentDate = new Date()
  const firstDay = new Date(currentDate.setDate(1))
  const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0)
  const year = firstDay.getFullYear() //获取当前年
  const month = String(firstDay.getMonth() + 1).padStart(2, '0') //获取当前月
  const lastDayOfMonth = lastDay.getDate() //获取当前月的天
  // return [firstDay, lastDay]
  return [`${year}-${month}-01 00:00:00`, `${year}-${month}-${lastDayOfMonth} 23:59:59`]
}

const defaultTime = ref(getCurrentMonthDates())
const chooes = ref<String[]>([])
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },

  {
    field: 'courseName',
    label: '课程名称',
    form: {
      hidden: true
    },
    sortable: true,
    slots: {
      default: (data: any) => {
        if (data.row.remark == '补考') {
          return (
            <>
              <div style="color:red">{data.row.courseName}(补考)</div>
            </>
          )
        } else {
          return <>{data.row.courseName}</>
        }
      }
    }
  },
  {
    field: 'examTime',
    label: '计划时间',
    search: {
      hidden: true
    },
    sortable: true
  },
  {
    field: 'userName',
    label: '计划讲师',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    sortable: true,
    slots: {
      default: (data: any) => {
        let arr: string[] = []
        if (data.row.teacherUsers) {
          JSON.parse(data.row.teacherUsers).map((i) => {
            arr.push(i.UserName)
          })
        }
        return <>{arr.toString()}</>
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          let arr: string[] = []
          if (data.teacherUsers) {
            JSON.parse(data.teacherUsers).map((i) => {
              arr.push(i.UserName)
            })
          }
          return <>{arr.toString()}</>
        }
      }
    }
  },

  {
    field: 'examTeacher',
    label: '讲师',
    form: {
      hidden: true
    },
    sortable: true,
    slots: {
      default: (data: any) => {
        if (data.row.examTeacher) {
          return <>{JSON.parse(data.row.examTeacher)?.UserName || ''}</>
        } else {
          return <></>
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{JSON.parse(data.examTeacher)?.UserName || ''}</>
        }
      }
    }
  },
  // {
  //   field: 'userIntroduce',
  //   label: '讲师介绍',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   }
  // },
  // {
  //   field: 'planTime',
  //   label: '计划培训时间',
  //   search: {
  //     hidden: true
  //   }
  // },

  {
    field: 'examStartTime',
    label: '考试开始时间',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
    // detail: {
    // slots: {
    // default: (data: any) => {
    // return (
    // <>
    //  {/* {data.examStartTime} 一 {data.examEndTime} */}
    // {/* </> */}
    // )
    // }
    // }
    // }
  },
  {
    field: 'examEndTime',
    label: '考试结束时间',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    sortable: true
  },

  {
    field: 'planUsersGuid',
    label: '计划学员数量',
    search: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        let arr: string[] = []
        if (data.row.planUsers) {
          JSON.parse(data.row.planUsers).map((i) => {
            arr.push(i.UserName)
          })
        }
        return <>{arr.length}</>
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          let arr: string[] = []
          if (data.planUsers) {
            JSON.parse(data.planUsers).map((i) => {
              arr.push(i.UserName)
            })
          }
          return <>{arr.length}</>
        }
      }
    },
    sortable: true
  },
  {
    field: 'planUsersGuid',
    label: '计划学员',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
      // slots: {
      //   default: (data: any) => {
      //     let arr: string[] = []
      //     if (data.row.planUsers) {
      //       JSON.parse(data.row.planUsers).map((i) => {
      //         arr.push(i.UserName)
      //       })
      //     }
      //     return <>{arr.toString()}</>
      //   }
      // }
    },
    detail: {
      slots: {
        default: (data: any) => {
          let arr: string[] = []
          if (data.planUsers) {
            JSON.parse(data.planUsers).map((i) => {
              arr.push(i.UserName)
            })
          }
          return <>{arr.toString()}</>
        }
      }
    }
  },
  {
    field: 'planUsersGuid',
    label: '实际学员数量',
    search: {
      hidden: true
    },
    // slots: {
    // default: (data: any) => {
    // let arr: string[] = []
    // if (data.row.examUsers) {
    // JSON.parse(data.row.examUsers).map((i) => {
    // arr.push(i.UserName)
    // })
    // }
    // return <>{arr.length}</>
    // }
    // },
    detail: {
      slots: {
        default: (data: any) => {
          let arr: string[] = []
          if (data.examUsers) {
            JSON.parse(data.examUsers).map((i) => {
              arr.push(i.UserName)
            })
          }
          return <>{arr.length}</>
        }
      }
    },
    table: { hidden: true }
  },
  {
    field: 'examUsers',
    label: '实际参加学员',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    // table: {
    //   slots: {
    //     default: (data: any) => {
    //       let arr: string[] = []
    //       if (data.row.examUsers) {
    //         JSON.parse(data.row.examUsers).map((i) => {
    //           arr.push(i.UserName)
    //         })
    //       }
    //       return <>{arr.toString()}</>
    //     }
    //   }
    // },
    detail: {
      slots: {
        default: (data: any) => {
          let arr: string[] = []
          if (data.examUsers) {
            JSON.parse(data.examUsers).map((i) => {
              arr.push(i.UserName)
            })
          }
          return <>{arr.toString()}</>
        }
      }
    },
    table: { hidden: true }
  },
  {
    field: 'planUsersGuid',
    label: '缺考学员数量',
    search: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          let len

          if (data.planUsers) {
            len = null
          }
          if (data.examUsers) {
            len = JSON.parse(data.planUsers).length - JSON.parse(data.examUsers).length
          }
          return <>{len}</>
        }
      }
    },
    table: { hidden: true }
  },
  {
    field: 'planUsersGuid',
    label: '缺考学员',
    search: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          let arr: string[] = []

          if (data.planUsers && data.examUsers) {
            let planUsers = JSON.parse(data.planUsers)
            let examUsers = JSON.parse(data.examUsers)
            planUsers.map((i) => {
              if (!examUsers.some((j) => j.UserName === i.UserName)) {
                arr.push(i.UserName)
              }
            })

            return <>{arr.toString()}</>
          } else {
            return <></>
          }
        }
      }
    },
    table: { hidden: true }
  },

  {
    field: 'releasePlanCount',
    label: '下发数量',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },

    sortable: true
  },
  {
    field: 'releaseExamCount',
    label: '已下发数量',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },

    sortable: true
  },
  {
    field: 'examStatus',
    label: t('menu.status'),
    width: '80px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag size="small" type={data.row.examStatus === 1 ? 'success' : 'danger'}>
              {data.row.examStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}
            </ElTag>
          </>
        )
      }
    },
    form: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data) => {
          return <>{data.examStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}</>
        }
      }
    },
    search: {
      component: 'Select',
      value: [],
      componentProps: {
        placeholder: '请选择'
      },
      optionApi: async () => {
        return [
          { label: t('userDemo.over'), value: 1 },
          { label: t('userDemo.naver'), value: 0 }
        ]
      }
    }
  },
  {
    field: 'planReleaseStatus',
    label: t('menu.ostatus'),
    width: '100px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag size="small" type={data.row.planReleaseStatus === 1 ? 'success' : 'danger'}>
              {data.row.planReleaseStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}
            </ElTag>
          </>
        )
      }
    },
    form: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data) => {
          return <>{data.planReleaseStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}</>
        }
      }
    },
    search: {
      component: 'Select',
      value: [],
      componentProps: {
        placeholder: '请选择'
      },
      optionApi: async () => {
        return [
          { label: t('userDemo.over'), value: 1 },
          { label: t('userDemo.naver'), value: 0 }
        ]
      }
    }
  },
  {
    field: 'resitScore',
    label: '及格线',
    search: {
      hidden: true
    },
    sortable: true
  },
  // {
  //   field: 'totalScore',
  //   label: '总分',

  //   search: {
  //     hidden: true
  //   },
  //   sortable: true,
  //   table: { hidden: true }
  // },
  // {
  //   field: 'avgScore',
  //   label: '平均分',

  //   search: {
  //     hidden: true
  //   },
  //   sortable: true,
  //   table: { hidden: true }
  // },
  {
    field: 'remark',
    label: t('common.remark'),
    form: {
      component: 'Input'
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    sortable: true
  },
  {
    field: 'date',
    label: t('problem.time'),
    search: {
      component: 'DatePicker',
      value: defaultTime.value,
      componentProps: {
        style: { width: '340px' },
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        StartPlaceholder: 'Start date',
        EndPlaceholder: 'End date'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'left',
    fixed: 'right',
    width: 240,
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },

    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row
          return (
            <>
              {haspermiss.value.includes('编辑') &&
              row.planReleaseStatus == 0 &&
              row.remark != '补考' ? (
                <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                  {t('exampleDemo.edit')}
                </BaseButton>
              ) : null}
              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              {haspermiss.value.includes('删除') && data.row.planReleaseStatus === 0 ? (
                <BaseButton type="danger" onClick={() => delData(data.row)}>
                  {t('exampleDemo.del')}
                </BaseButton>
              ) : null}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = { ...row }
  dialogVisible.value = true
  if (type == 'edit') {
    let arr: String[] = []
    if (row.planUsers) {
      JSON.parse(row.planUsers).map((i) => {
        arr.push(i.UserNo + '$' + i.UserName + '$' + i.DepNo + '$' + i.DepName)
      })
    }
    let tarr: String[] = []
    if (row.teacherUsers) {
      JSON.parse(row.teacherUsers).map((i) => {
        tarr.push(i.UserNo + '$' + i.UserName + '$' + i.DepNo + '$' + i.DepName)
      })
    }
    let planTime: string[] = []
    if (row.examTime) {
      const time = row.examTime.split(' 至 ')
      planTime = [time[0], time[1]]
      console.log('planTime', planTime)
    }
    currentRow.value = { ...row, chooes: arr, chooesTeachers: tarr, planTime: planTime }
  }
  // else {
  //   crudSchemas.forEach((item) => {
  //     if (item.field == 'planUsersGuid') {
  //       if (item.form) {
  //         let arr: String[] = []
  //         if (row.planUsers) {
  //           JSON.parse(row.planUsers).map((i) => {
  //             arr.push(i.UserNo + '$' + i.UserName)
  //           })
  //           chooes.value = arr
  //         }
  //         item.form.componentProps.modelValue = arr
  //       }
  //     }
  //   })
  // }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

// const filterDep = (value: string, data: DepartmentItem) => {}
const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
  chooes.value = []
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      console.log('formData---', formData)

      let res
      if (actionType.value == 'edit') {
        formData.guid = currentRow.value.guid
        res = await UpdatePlanExamApi(formData).finally(() => {
          saveLoading.value = false
        })
      } else {
        res = await AddCourseExamApi(formData).finally(() => {
          saveLoading.value = false
        })
      }
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" v-if="haspermiss.includes('新增')">{{
        t('exampleDemo.add')
      }}</BaseButton>
      <BaseButton
        :loading="delLoading"
        type="danger"
        @click="delData(undefined)"
        v-if="haspermiss.includes('删除')"
      >
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
      :showAction="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" :max-height="600">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
